#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import re

import FileHostProtoType


class mtuitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
        self.link = "http://www.multiupload.com/%s" % self.id
    
class multiupload(FileHostProtoType.FileHostProcess):            
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "MultiUpload" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
            
    def login(self):
        if self.islogin:
            return True
        if self._opener is not None:
            return False
        print >> self.fherr, 'login to MultiUpload %s/%s...' % (self._user,'*'*len(self._pwd))
        loginData = {'username' : self._user, 
                     'password' : self._pwd,
                     }
        loginresult =  self.loginFileHost(
                    'http://www.multiupload.com/login', 
                    loginData
                    )
        # you always see you username at the top of the page, if login successfully.
        if self._user.lower() not in loginresult.lower():
            self.fherr.write("User %s Failed to Login MegaUpload." % self._user)
            return False
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True
        return True
    
    def find(self, filenames = [], filelist = None):
        found = []
        if filelist == None:
            return found      
        filelistlower = [fl.name.lower() for fl in filelist]
        todel = []
        for fl in filenames:
            try:
                index = filelistlower.index(os.path.basename(fl).lower())
                found.append(filelist[index])
                todel.append(fl)
            except:
                continue
        for d in todel:
            filenames.remove(d)
        found.sort()
        return found
        
    def getFileList(self):
        self.fherr.write('Becasue MultiUpload\'s FileManage doesn\'t display full filename, program won\'t implement List funciton.')
        return []
    
    def upload_web(self, file, progressLog=None, other_args=None):
        #indexpage
        indexpage = self.post_request('http://www.multiupload.com').encode('utf8','ignore')
        reServer = re.compile('(?P<serverlink>http://www(\d+).multiupload.com/upload/\?UPLOAD_IDENTIFIER=(?P<identifier>\d+))')
        serverMatch = reServer.search(indexpage)
        if serverMatch is not None:
            serverlink = serverMatch.group('serverlink')
            identifier = serverMatch.group('identifier')
        else:            
            return
        
        reUserCookie = re.compile('<input type="hidden" name="u" value="(?P<usercookie>\w+)" id="usercookie">')
        ucMatch = reUserCookie.search(indexpage)
        if ucMatch is not None:
            usercookie = ucMatch.group('usercookie')
        else:
            return
        #upload
        message = 'airu-upload'
        if other_args:
            message = other_args.get('message','airu-upload')            
        data = {'file0':open(file, 'rb'),
                'description_0':message,
                'UPLOAD_IDENTIFIER':identifier,
                'u':usercookie,
                'fetchdesc3':'',
                'fetchfield4':'http://',
                'fetchdesc4':'',
                'fetchfield5':'http://',
                'fetchdesc5':'',
                'fetchfield6':'http://',
                'fetchdesc6':'',
                'fetchfield7':'http://',
                'fetchdesc7':'',
                'fetchfield8':'http://',
                'fetchdesc8':'',
                'fetchfield9':'http://',
                'fetchdesc9':'',
                'service_1':'1',
                'service_16':'1',
                'service_7':'1',
                'service_9':'1',
                'service_17':'1',
                'service_6':'1',
                'service_15':'1',
                'service_14':'1',
                'service_18':'1',
                'fromemail':'',
                'toemail':'',
                'username_1':'',
                'password_1':'',
                'remember_1':'1',
                'username_16':'',
                'password_16':'',
                'remember_16':'1',
                'username_7':'',
                'password_7':'',
                'remember_7':'1',
                'username_9':'',
                'password_9':'',
                'remember_9':'1',
                'username_17':'',
                'password_17':'',
                'remember_17':'1',
                'username_6':'',
                'password_6':'',
                'remember_6':'1',
                'username_15':'',
                'password_15':'',
                'remember_15':'1',
                'username_14':'',
                'password_14':'',
                'remember_14':'1',
                'username_18':'',
                'password_18':'',
                'remember_18':'1',
                }
        
        self.fherr.write("Uploading...%s" % file)
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_file(serverlink, data, self.get_cookies(), callback=callback)
        
        #result
        startpos = result.find('{')
        endpos = result.find('}') + 1
        resultDict = {}
        exec('resultDict = %s' % result[startpos:endpos])
        item = mtuitem(os.path.basename(file), 'file', resultDict['downloadid'], '', self.rename_func(file))
        self.newupload.append(item)
        self.fhout.write(item.format()) 
        return item